package com.mavenq.fly.websocket.client;

import com.mavenq.fly.utils.JsonUtils;
import com.mavenq.fly.websocket.entity.WSMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.PreDestroy;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class WSClientService {

    private final WebSocketClient client = new StandardWebSocketClient();
    private WebSocketSession session;

    public CompletableFuture<WebSocketSession> connect(String uri) {
        CompletableFuture<WebSocketSession> future = new CompletableFuture<>();
        try {
            session = client.doHandshake(new TextWebSocketHandler() {
                @Override
                public void afterConnectionEstablished(WebSocketSession session) {
                    log.info("WSClient 已连接：{}", session.getId());
                    future.complete(session);
                }

                @Override
                protected void handleTextMessage(WebSocketSession session, TextMessage message) {
                    log.info("WSClient 收到：{}", message.getPayload());
                }

                @Override
                public void handleTransportError(WebSocketSession session, Throwable exception) {
                    log.error("WSClient 传输错误：{}", session.getId(), exception);
                    future.completeExceptionally(exception);
                }

                @Override
                public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
                    log.info("WSClient 连接关闭：{}，状态={}", session.getId(), status);
                }
            }, uri).get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            future.completeExceptionally(e);
        }
        return future;
    }

    public void send(WSMessage msg) {
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(JsonUtils.toJson(msg)));
            } catch (Exception e) {
                log.error("WSClient 发送失败", e);
            }
        } else {
            log.warn("WSClient 未连接，无法发送：{}", msg.getType());
        }
    }

    @PreDestroy
    public void disconnect() throws Exception {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
}